<template>
  <div>
    <div class="main_operation">
      <div class="operation_left">
        <a-button v-if="routerShow($route,'role_add')" class="mr10" type="primary" @click="addBtn">添加</a-button>
        <!-- <a-button class="mr10" type="danger" @click="">批量删除</a-button> -->
      </div>
      <div class="operation_right">
        <a-select allowClear class="mr10" style="width: 220px" placeholder="请选择角色等级">
          <a-select-option value="1">一级</a-select-option>
          <a-select-option value="2">二级</a-select-option>
          <a-select-option value="3">三级</a-select-option>
        </a-select>
        <!-- 				<a-select class="mr10" style="width: 200px" placeholder="请选择账号">
	                <a-select-option value="jack">平台管理员账号</a-select-option>
	                <a-select-option value="lucy">二级平台管理员账号</a-select-option>
	            </a-select> -->
        <a-input-search placeholder="请输入角色名称" enterButton="查询" /><!-- @search="onSearch" -->
      </div>
    </div>
    <div class="main">
     <a-table :pagination="false" :loading="tableLoad" :columns="Fields"
        :dataSource="dataLists.data" :rowKey="record => record.id" :scroll="{x: 1200, y: 500 }">
        <template slot="action" slot-scope="text, record">
          <a-button v-if="routerShow($route,'rolePermission_roleDetail')" size="small" class="mr5" type="primary" @click="power(record)">权限</a-button>
          <a-button v-if="routerShow($route,'role_detail')" size="small" class="mr5" type="primary" @click="details(record)">详情</a-button>
          <a-button v-if="routerShow($route,'role_update')" size="small" class="mr5" type="primary" @click="editBtn(record)">编辑</a-button>
          <a-button v-if="routerShow($route,'role_delete')" size="small" type="danger" @click="delBtn(record)">删除</a-button>
        </template>
      </a-table>
    </div>
    <div class="pageBox">
      <a-pagination
        :total="dataLists.total"
        :showTotal="total => `共 ${total} 条数据`"
        :pageSize="dataLists.per_page"
        :defaultCurrent="1"
        @change="pageChange"
      />
    </div>
    <!-- 添加编辑 -->
    <a-modal
      :destroyOnClose="true" :title="titleModel" :width="600"
      v-model="visible" :confirmLoading="confirmLoading"
      @ok="handleOk" @cancel="handleCancel">
      <a-form>
        <a-form-item required label="角色名称:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
          <a-input v-model="formItem.role_name" placeholder="请输入角色名称" />
        </a-form-item>
        <a-form-item label="角色等级:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
          <a-select v-model="formItem.role_grade" placeholder="请选择角色等级">
            <a-select-option :value="1">平台</a-select-option>
            <a-select-option :value="2">代理</a-select-option>
            <a-select-option :value="3">公司</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色描述:" :label-col="{ md: 5,xs:24 }" :wrapper-col="{ md: 18,xs:24 }">
          <a-textarea v-model="formItem.describe" placeholder="请输入角色描述" :autosize="{ minRows: 3, maxRows: 6 }" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 详情 -->
    <a-modal :destroyOnClose="true" title="详情" v-model="detaiVisible">
      <template slot="footer">
        <a-button key="submit" type="primary" @click="detaiVisible = false">确定</a-button>
      </template>
      <ul class="modalUl">
        <li><span>角色名称: </span>{{itemDetail.role_name}}</li>
        <li><span>角色等级: </span>{{itemDetail.role_grade_name}}</li>
        <li><span>创建时间: </span>{{itemDetail.created_at}}</li>
        <li><span>角色描述: </span>{{itemDetail.describe}}</li>
      </ul>
    </a-modal>
    <!-- 权限 -->
    <a-modal
      :destroyOnClose="true" title="权限设置" :width="600"
      v-model="powerVisible" :confirmLoading="confirmLoading"
      @ok="powerOk" @cancel="powerCancel">
      <a-button class="mr10" type="primary" @click="freeOpen">全部展开</a-button>
      <a-button class="mr10" type="primary" @click="freeClose">全部收缩</a-button>
      <a-button type="primary" @click="freeAll">{{isBtnText}}</a-button>
      <div class="mt10" style="max-height: 400px; overflow:auto;border: 1px solid #ddd;">
        <a-tree
          ref="tree"
          v-if="powerVisible"
          checkable
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          v-model="checkedKeys"
          :treeData="permissAll"
          @check="treeChick"
          checkStrictly
        >
          <template slot="isPay" slot-scope="record">
            {{record.title}} &nbsp;&nbsp;&nbsp;&nbsp;
            <a-switch checkedChildren="收费" @change="val=>aaa(val,record)" unCheckedChildren="免费" v-model="currentPermissionId[record.key]" />
          </template>
          <!--  -->
        </a-tree>
      </div>
    </a-modal>
  </div>
</template>

<script>
  import { mapState, mapActions } from 'vuex';
  export default {
    name: "Role",
    data() {
      return {
        /* 通用模块 */
          //列表
        tableLoad: false,//列表loading状态
        formList:{          //列表信息
					page: 1
				},
        selectedRowKeys: [],//勾选的id
        /* 通用模块end */

        /* 权限 */
        currentPermissionId: [],//当前角色id
        powerVisible: false,//权限窗口开关
        expandedKeys: [],//展开指定的树节点
        autoExpandParent: true,//是否自动展开父节点
        checkedKeys: {
          checked:[],
          halfChecked: []
        },  //勾选框勾选的key
        powerForm: {      
          permission_id: [],
          role_id: '',
        },

        /* 详情 */
        detaiVisible: false,//窗口开关

        /* 添加编辑 */
        titleModel: '',//标题
        visible: false,//窗口显示隐藏
        confirmLoading: false,//按钮loading状态
				formItem:{
					role_name: '',//角色名，必填
					role_grade: 1,//角色等级，默认1
					describe: '',//描述
				},
        /* 添加编辑end */
      }
    },
    computed: {
    	...mapState({
    		Fields: state => state.Role.Fields,
    		dataLists: state => state.Role.dataLists,
    		requestCode: state => state.Role.requestCode,
    		itemDetail: state => state.Role.itemDetail,
    		permissAll: state => state.Role.permissAll,
    	}),
      //全选全不选按钮文字计算
      isCheckedKeys(){
        return this.checkedKeys.checked
      },
      isBtnText() {
        if( this.isCheckedKeys.length == 0 && this.isCheckedKeys.checked == undefined){
          return "全选"
        } else {
          return "全不选"
        }
      },
    },
    // watch: {
    //   permissAll(){
    //     this.permissAllData = this.permissAll.concat()
    //   }
    // },
    mounted() {
      this.permissionAll()
      this.changeData()
    },
    methods: {
      aaa(value,item) {
        console.log(this.currentPermissionId,item);
      },
      treeChick(checkeds, e){
        console.log('握草',this.checkedKeys);
        console.log(checkeds, e);
        console.log('当前勾选', e.node.dataRef);
        let currentClick = e.node.dataRef     //当前点击的复选框数据
        if (e.checked) {                          //判断是否选中
          if (currentClick.children != undefined) {
            // console.log("勾选一级默认选中当前所有2级");
            currentClick.children.map(item=>{
              this.checkedKeys.checked.splice(this.checkedKeys.checked.length-1,0,item.key)
            })
            return null
          }
          let dataAll = this.$refs.tree.treeData  //拿到tree所有数据
          dataAll.map(item=>{                     //查找判断一级有没有二级
            if (item.children.length || item.children != undefined ) { 
              item.children.map(twoItem=>{
                // 判断二级是否有当前点击的key
                if (twoItem.key == currentClick.key) {
                  //if父级的key是否已经勾选，没有就勾选
                  if (!this.checkedKeys.checked.includes(item.key)) {
                    this.checkedKeys.checked.splice(this.checkedKeys.checked.length-1,0,item.key)
                  }
                }
              })
            }
          })
        } else {
          /* 取消一级勾选时去掉子级所有勾选 */
          if (currentClick.children != undefined) {
            currentClick.children.forEach(item=>{
              this.checkedKeys.checked.remove(item.key)
            })
          }
          
        }
        console.log('当前选中All',this.checkedKeys.checked);
      },
      ...mapActions({
				getLists: 'Role/roleLists',     //列表
        dataAdd: 'Role/roleAdd',        //添加
				dataEdit: 'Role/roleEdit',      //编辑
				dataDel: 'Role/roleDel',        //删除
				dataDetail: 'Role/roleDetail',  //详情
				permissionAll: 'Role/permissionAll',  //权限列表所有信息
				setPower: 'Role/setPower',  //权限批量操作
			}),

      /* 通用模块 */
        // 勾选
      onSelectChange(selectedRowKeys) {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys
      },
        // 重新获取列表数据
      changeData(){
        this.tableLoad = true
        setTimeout(()=> {
          this.getLists(this.formList)
          this.tableLoad = false
        }, 800);
      },
        // 页码
			pageChange(page) {
				this.formList.page = page;
				this.getLists(this.formList)
			},
      /* 通用模块end */

      /* 添加编辑 */
        // 添加
      addBtn() {
        this.titleModel = '添加角色'
        this.formItem = {
        	role_name: '',//角色名，必填
        	role_grade: 1,//角色等级，默认1
        	describe: '',//描述
        }
        this.visible = true
      },
        // 编辑
      editBtn(item) {
        console.log(item);
        this.titleModel = '编辑角色'
        this.formItem.id = item.id
        this.formItem.role_name = item.role_name
        this.formItem.role_grade = item.role_grade
        this.formItem.describe = item.describe
        this.visible = true
      },
        // 窗口确定
      handleOk() {
				this.confirmLoading = true;
        if(this.titleModel == '添加角色') {
          this.formList.page = 1;
          this.dataAdd(this.formItem)
        } else {
          this.dataEdit(this.formItem)
        }
				setTimeout(() => {
          // console.log(this.requestCode);
          if(this.requestCode === 0) {
            this.visible = false;
            this.changeData()
          }
					this.confirmLoading = false;
				}, 1000);
			},
        // 窗口取消
      handleCancel() {
        this.visible = false
      },
      /* 添加编辑end */

      /* 删除 */
      delBtn(item) {
        let _this = this
        this.$confirm({
					title: `您确定要删除 ${item.role_name} 吗?`,
					content: `删除后将不可恢复,请仔细核对!`,
					okText: '确定',
					okType: 'danger',
					cancelText: '取消',
					onOk() {
						_this.dataDel(item.id)
						_this.changeData()
					},
				});
      },
      /* 详情 */
      details(item){
        this.dataDetail(item.id)
        this.detaiVisible = true
      },

      /* 权限设置 */
       //展开
      freeOpen(){
        this.expandedKeys = []
        this.permissAll.forEach((item, i)=>{
          this.expandedKeys.push(item.key)
        })
      },
       //关闭
      freeClose(){
        this.expandedKeys = []
      },
       //全选 <=> 全不选
      freeAll(){
        if( this.checkedKeys.checked.length == 0 ){
          let arr = []
          this.permissAll.forEach((item, i) => {
            arr.push(item.key)
            item.children.forEach((childitem,idx) => {
              arr.push(childitem.key)
            })
            this.checkedKeys = {
              checked: arr,
              halfChecked: []
            }
          })
        } else {
          this.checkedKeys = {
            checked: [],
            halfChecked: []
          }
        }
      },
       // 打开节点
      onExpand (expandedKeys) {
        console.log('onExpand', expandedKeys)
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      
      isBool(value) {
        if (value === 1) {
          return true
        }
        return false
      },
       // 权限按钮
      power(item) {
        console.log(item,this.permissAll);
        this.checkedKeys.checked = []  //勾选框勾选的key
        this.expandedKeys = []//展开指定的树节点
        this.currentPermissionId = []
        this.powerForm = {      
          permission_id: [],
          role_id: item.id,
        }
        item.permission.map((idItem, i)=>{
          this.checkedKeys.checked.push(idItem.permission_id)
          this.currentPermissionId[idItem.permission_id] = this.isBool(idItem.is_pay)
        })
        this.powerVisible = true
      },
       // 窗口确定
      powerOk() {
        this.confirmLoading = true;
        console.log('确定的握草1',this.checkedKeys);
        this.powerForm.permission_id
        if (typeof this.checkedKeys.checked != 'undefined' && this.checkedKeys.checked.length > 0) {
          this.checkedKeys.checked.forEach(item=>{
            // console.log('下标'+item,this.currentPermissionId[item]);
            // 一级模块全部免费0
            this.powerForm.permission_id[item] = 0
            if (this.currentPermissionId.hasOwnProperty(item)) {
              // 二级收付费
              this.powerForm.permission_id[item] = this.currentPermissionId[item] == true ? 1 : 0
            }
          })
        }
        // this.powerForm.permission_id，下标为权限id，值为收付费提交
        this.setPower(this.powerForm)
        setTimeout(() => {
          if(this.requestCode === 0) {
            this.powerVisible = false;
            this.changeData()
          }
        	this.confirmLoading = false;
        }, 1000);
      },
       // 窗口取消
      powerCancel() {
        this.powerVisible = false
      },
      /* 权限end */
    }
  }
</script>

<style lang="less" scoped>
  .modalUl {
    font-size: 16px;
    li {
      margin-bottom: 10px;
      span {
        font-weight: bold;
        margin-right: 10px;
      }
    }
  }
</style>
